package com.gin.kotlin.gf2gamecommunity.composable

import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.lifecycle.viewmodel.compose.viewModel
import com.gin.kotlin.gf2gamecommunity.R
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.util.contentFileInfo
import com.gin.kotlin.gf2gamecommunity.base.util.copyFile
import com.gin.kotlin.gf2gamecommunity.base.util.findSource
import com.gin.kotlin.gf2gamecommunity.viewmodel.UploadViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import java.io.File
import java.util.UUID

@Composable
fun ImageUploadIconButton(uploadViewModel: UploadViewModel = viewModel(), onUploaded: suspend CoroutineScope.(htmlImage: String, source: String?) -> Unit) {
    val tag = "ImageUploadIconButton"
    val tempDir = File(LocalContext.current.cacheDir, "upload_temp").also { it.mkdirs() }
    val contentResolver = LocalContext.current.contentResolver
    val coroutineScope = rememberCoroutineScope()
    // 启动文件选择器
    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent(),
        onResult = { uri ->
            if (uri == null) {
                App.toast("未选择文件")
            } else {
                contentResolver.apply {
                    // 文件信息
                    val contentFileInfo = contentFileInfo(uri)
                    if (contentFileInfo == null) {
                        App.toast("文件信息获取失败")
                    } else if (contentFileInfo.mimeType?.startsWith("image") != true) {
                        App.toast("只能上传图片")
                    } else {
                        // 目标文件
                        val filename = contentFileInfo.originalName ?: "${UUID.randomUUID()}.${contentFileInfo.ext}"
                        Log.i(tag, "复制图片: $filename")
                        val destFile = File(tempDir, filename).also { it.delete() }
                        // 复制文件
                        copyFile(uri, destFile)
                        val source = findSource(filename)
                        Log.i(tag, "图片来源: $source")

                        coroutineScope.launch {
                            Log.i(tag, "上传图片: $filename")
                            App.toast("上传图片: $filename")
                            try {
                                val htmlImage = uploadViewModel.upload(destFile)
                                App.toast("上传完毕 $filename")
                                onUploaded(htmlImage, source)
                            } catch (e: Exception) {
                                App.toast("上传失败: ${e.message}")
                            }
                        }
                    }
                }
            }
        }
    )

    IconButton(onClick = { launcher.launch("*/*") }) {
        Icon(painterResource(R.drawable.ic_image_24), contentDescription = "上传图片")
    }
}